package com.leyou.user.interceptors;

import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.user.config.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
@EnableConfigurationProperties(JwtProperties.class)
public class PrivilegeInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties prop;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            String token = request.getHeader(prop.getApp().getHeaderName());
            Payload<AppInfo> appInfoPayload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), AppInfo.class);
            AppInfo info = appInfoPayload.getInfo();
            List<Long> targetList = info.getTargetList();
            if (targetList.contains(prop.getApp().getId())){
                return true;
            }
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.SERVER_ACCESS_ERROR);
        }
        return false;
    }
}
